<?php

/**
 * Worker
 * 
 * @author ShuangYa
 * @package Demo
 * @category Worker
 * @link http://www.sylingd.com/
 * @copyright Copyright (c) 2015 ShuangYa
 */

class Worker {
	public static function init() {
		self::sign();
	}
	public static function sign() {
		$users = Sy::model('member')->getList();
		//获取喜欢的列表
		foreach ($users as $user) {
			self::signOneUser($user);
		}
	}
	public static function signOneUser($user, $retry = 0) {
		if ($retry > 2) {
			echo '获取用户失败', "\n";
			return;
		}
		echo '获取用户 ', $user['uname'], "\n";
		try {
			if ($user['morethan200'] == 1) {
				$userlike = \TiebaPersonal::getMyLikeSlow($user['bduss'], $user['stoken']);
			} else {
				$userlike = \TiebaPersonal::getMyLike($user['bduss']);
			}
		} catch (\Exception $e) {
			self::signOneUser($user, $retry + 1);
			return;
		}
		echo '共', count($userlike), '个贴吧', "\n";
		foreach ($userlike as $tb) {
			self::signOneTb($user['bduss'], $tb);
			sleep(0.5);
		}
		echo '用户 ', $user['uname'], '签到完成', "\n";
	}
	public static function signOneTb($BDUSS, $tb, $retry_count = 0) {
		if ($retry_count > 3) {
			echo $tb['name'], '吧：签到失败', "\n";
			return;
		}
		$retry_count++;
		try {
			$r = \TiebaPersonal::sign($BDUSS, $tb['name'], $tb['id']);
		} catch (\Exception $e) {
			self::signOneTb($BDUSS, $tb, $retry_count);
			return;
		}
		//是否需要重试
		echo $tb['name'], '吧：';
		if ($r[0] === 0) {
			$retry = FALSE;
			switch ($r[1]) {
				case 'signed':
					echo '已签到过';
					break;
				case 'tieba_blocked':
					echo '该吧被屏蔽';
					break;
				case 'wrong_cookie':
					echo 'Cookie失效';
					break;
				case 'server_unknow':
					echo '服务器出错，重试';
					$retry_count--; //服务器出错则重试次数减一，即不加一
					$retry = TRUE;
					break;
				default:
					echo '失败，重试';
					$retry = TRUE;
			}
			echo "\n";
			if ($retry) {
				sleep(1);
				self::signOneTb($BDUSS, $tb, $retry_count);
			}
		} else {
			echo '签到成功', "\n";
		}
	}
}